package com.hertz.appr.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.util.HtmlUtils;


public class Util {

	private static Map<String,SimpleDateFormat> formatMap = new HashMap<String,SimpleDateFormat>();
	
	public static Date parseDate(String str, String format) throws WeiboException{
        if(str==null||"".equals(str)){
        	return null;
        }
    	SimpleDateFormat sdf = formatMap.get(format);
        if (null == sdf) {
            sdf = new SimpleDateFormat(format);
            formatMap.put(format, sdf);
        }
        try {
            synchronized(sdf){
                // SimpleDateFormat is not thread safe
                return sdf.parse(str);
            }
        } catch (ParseException pe) {
            throw new WeiboException("Unexpected format(" + str + ") returned");
        }
    }
	
	public static String parseDate(Long timestamp,String format) throws Exception{
		SimpleDateFormat sdf = formatMap.get(format);
		 if (null == sdf) {
	            sdf = new SimpleDateFormat(format);
	            formatMap.put(format, sdf);
	     }
		 return sdf.format(new Date(timestamp));
	}
	
	public static String parseDate(Date date,String format) throws Exception{
		SimpleDateFormat sdf = formatMap.get(format);
		 if (null == sdf) {
	            sdf = new SimpleDateFormat(format);
	            formatMap.put(format, sdf);
	     }
		 return sdf.format(date);
	}
	
	/**
	 * yyyyMMdd
	 * yyyyMMdd-HH:mm:ss
	 * @param endTime
	 * @return
	 */
	public static boolean isEndTime(String endTime){
		if(StringUtils.isBlank(endTime)){
			return false;
		}
		String ymdhms = "\\d{8}-\\d{2}:\\d{2}:\\d{2}";
		String ymd = "\\d{8}";
		if(!endTime.matches(ymdhms) && !endTime.matches(ymd)){
			return false;
		}
		boolean d1 = false;
		try {
			parseDate(endTime, "yyyyMMdd");
			d1 = true;
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		
		boolean d2 = false;
		try {
			System.out.println(parseDate(endTime, "yyyyMMdd-HH:mm:ss"));
			
			d2 = true;
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		if(d1 || d2)
			return true;
		else
			return false;
	}
	
	public static Long timestamp10to13(Long shortTimestamp){
		Long longTimestamp = shortTimestamp;
		if(shortTimestamp.toString().length() < 13){
			int append = 13 - shortTimestamp.toString().length();
			for(int i = 0; i < append; i++){
				longTimestamp = longTimestamp * 10;
			}
			return longTimestamp;
		}else{
			return shortTimestamp;
		}
	}
	
}
